package cn.maidouya.pay.service.impl;


import cn.maidouya.basic.exception.BusinessExcepiton;
import cn.maidouya.basic.service.impl.BaseServiceImpl;
import cn.maidouya.order.service.IProductOrderService;
import cn.maidouya.pay.constants.OrderConstants;
import cn.maidouya.pay.domain.AlipayInfo;
import cn.maidouya.pay.domain.PayBill;
import cn.maidouya.pay.domain.PayFlow;
import cn.maidouya.pay.mapper.AlipayInfoMapper;
import cn.maidouya.pay.mapper.PayBillMapper;
import cn.maidouya.pay.mapper.PayFlowMapper;
import cn.maidouya.pay.service.IPayBillService;
import cn.maidouya.pay.utils.AlipayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayBillServiceImpl extends BaseServiceImpl<PayBill> implements IPayBillService {

    @Autowired
    private AlipayInfoMapper alipayInfoMapper;

    @Autowired
    private PayBillMapper payBillMapper;

    @Autowired
    private IProductOrderService productOrderService;
    @Autowired
    private PayFlowMapper payFlowMapper;

    /**
     *   统一支付接口
     * @param bill
     * @return
     */
    @Override
    public String pay(PayBill bill) {
        // 第一步：较空
        if (bill == null) {
            throw new BusinessExcepiton("请创建支付单再进行支付");
        }
        // 第二步：较空数据表订单
        PayBill payBill = payBillMapper.loadByUnionPaySn(bill.getUnionPaySn());
        if (payBill == null){
            throw new BusinessExcepiton("请创建支付单再进行支付");
        }
        // 第三步：选择支付方式   0 余额 1 支付宝 2 微信 3 银联
        switch (payBill.getPayChannel().intValue()){
            case 1: // 支付宝
                AlipayInfo info = alipayInfoMapper.loadByShopId(bill.getShop_id()); // 查询领养宠物是哪个店铺
                // 调用统一支付接口
                return AlipayUtils.pay(info, bill); // 返回对象
            case 2: // 微信
                break;
            case 3: // 银联
                break;
            default: // 余额
        }
        return null;
    }

    @Override
    public PayBill loadByUnionPaySn(String unionPaySn) {
        return payBillMapper.loadByUnionPaySn(unionPaySn);
    }
    // 支付流水
    @Override
    public void saveFlow(PayBill bill) {
        PayFlow flow = initPayFlow(bill);
        payFlowMapper.save(flow);
    }

    private PayFlow initPayFlow(PayBill bill) {
        PayFlow flow = new PayFlow();
        flow.setUser_id(bill.getUser_id());
        flow.setNickName(bill.getNickName());
        flow.setMoney(bill.getMoney());
        flow.setType(bill.getPayChannel());
        flow.setBusinessType(OrderConstants.BUSINESS_TYPE_ACQUISITION_ORDER);
        flow.setBusinessKey(bill.getBusinessKey());
        flow.setBusinessName(bill.getDigest());
        flow.setType(bill.getPayChannel());
        flow.setPayChannel(bill.getPayChannel());
        flow.setPayChannelName(bill.getDigest());
        flow.setDigest(bill.getDigest());
        flow.setUnionPaySeq(bill.getUnionPaySn());
        return flow;
    }
}